import React, {useEffect} from 'react';
import {
    Alert, BackHandler,
    Dimensions,
    Image, Keyboard,
    SafeAreaView,
    TextInput,
    ToastAndroid,
    TouchableOpacity,
    TouchableWithoutFeedback,
    View,
} from "react-native";
import { StyleSheet } from 'react-native';
import {
    Button,
    Card,
    Divider,
    Icon,
    Input,
    Layout, List,
    Tab,
    TabView,
    Text,
    TopNavigation,
    TopNavigationAction
} from '@ui-kitten/components';


import FatchManager from "../Compoments/FatchManager"
import SorageManager from "../Compoments/SorageManager"
import {assertSourceType} from "@babel/core/lib/config/validation/option-assertions";
import AsyncStorage from "@react-native-async-storage/async-storage";


const data = new Array(8).fill({
    title: 'Item',
});

export const ServicingTicketScreen = ({ navigation }) => {

    //————————————————————————初始化值————————————————————————————//

    //搜索框
    const [value, setValue] = React.useState('');

    //顶部Tab 切换
    const [selectedIndex, setSelectedIndex] = React.useState(0);

    //机车信息
    const [trainInf, setTrainInf] = React.useState('');
    const [workInf, setWorkInf] = React.useState('');


    useEffect(()=>{

        //首次进入删除search
        SorageManager.set("search",'')

        /**
         * 首先从本地存储中获取用户基本信息
         * 根据搜索框中内容获取车辆信息
         */
        Keyboard.addListener("keyboardDidHide", _keyboardDidHide);

        SorageManager.get('userInf').then(async r => {
            const s = await AsyncStorage.getItem("search")
            console.log(s)
            if (s === undefined) {
                getPreparInfList(r["belongduan"], "")
                getExtractedList("", r["userid"])
            } else {
                getPreparInfList(r["belongduan"], s)
                getExtractedList(s, r["userid"])
            }

        } )

        // cleanup function
        return () => {
            Keyboard.removeListener("keyboardDidHide", _keyboardDidHide);
        };

    },[]);


    //————————————————————————fetch api————————————————————————————//

    /**
     *  根据 所属段 和  车号 获取 机车信息
     * @param jrd
     * @param ch
     */
    const getPreparInfList=(jrd,ch)=>{



        const  url = 'http://htjoa.nrnet.cn/dc14/jwmis/preparInf/preparInf';
        const formData =new FormData();
        formData.append("jrd",jrd);
        formData.append("ch",ch);

        console.log(formData)
        FatchManager.get(url,formData,(json)=>{
            console.log(json)
        },(json)=>{
            setTrainInf(json)
            console.log(json)
        },(e)=>{
            console.log(e)
        })
    }


    /**
     *  根据用户id 和 车辆id 提取 活项
     * @param rkid 传递参数为CH
     * @param hxtqr
     */
    const getExtractedList=(rkid,hxtqr)=>{

        const requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };
        fetch("http://htjoa.nrnet.cn/dc14/jwmis/ticketController/extracted?rkid="+rkid+"&hxtqr="+hxtqr, requestOptions)
            .then(response => response.json())
            .then(result => {
                console.log(result,"已提取活项");
                setWorkInf(result)
            })
            .catch(error => {
                console.log('error', error)
                console.log("请检查网络")
            });
    }


    /**
     * 删除已提活项
     * @private
     */
    const  deleteWork = (id)=>{
        const requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };
        fetch("http://htjoa.nrnet.cn/dc14/jwmis/zbclcrk/delete?id="+id, requestOptions)
            .then(response => response.json())
            .then(result => {
                console.log(result,"删除结果")
            })
    }

        //————————————————————————事件反馈——————————————————————————————//
    //监听键盘事件，缩回根据 搜索框内容重新加载
    const _keyboardDidHide = () => {
        console.log(value)
        SorageManager.get('userInf').then(async r => {
            const s = await AsyncStorage.getItem("search")

            if (s === undefined) {
                getPreparInfList(r["belongduan"], "")
            } else {
                getPreparInfList(r["belongduan"], s)
            }
        } )
    };

    //跳转页面至故障选择页面
    const navigateAddTicketCollection = (trainNumber) => {
        console.log("跳转到选择故障页面")
        console.log(trainNumber)
        navigation.navigate('AddTicketCollection',{ch:trainNumber});
    };

    //跳转回菜单页面
    const navigateMenu = () => {
        navigation.navigate('Menu');
    };

    //删除按钮
    const deleteButton = (info)=>{

        const requestOptions = {
            method: 'GET',
            redirect: 'follow'
        };
        const url = "http://htjoa.nrnet.cn/dc14/jwmis/zbclcrk/delete?id="+info.item.id;
        console.log(url)
        fetch(url, requestOptions)
            .then(response => response.json())
            .then(result => {
                console.log(result,"删除结果")
                if (result==="success"){
                    showToast("删除成功")
                }else {
                    showToast("遇到问题，删除失败")
                }

            })

        // Alert.alert("", "删除活项", [
        //     {
        //         text: "取消",
        //         onPress: () => null,
        //         style: "cancel"
        //     },
        //     { text: "确定", onPress: () => {
        //
        //             const requestOptions = {
        //                 method: 'GET',
        //                 redirect: 'follow'
        //             };
        //             const url = "http://htjoa.nrnet.cn/dc14/jwmis/zbclcrk/delete?id="+info.item.id;
        //             console.log(url);
        //             fetch(url, requestOptions)
        //                 .then(response => response.json())
        //                 .then(result => {
        //                     console.log(result,"删除结果")
        //                 })
        //         }}
        // ]);
    }


    //————————————————————————UI组件————————————————————————————————//


    const showToast = (message) => {
        ToastAndroid.show(message, ToastAndroid.SHORT);
    };

    const BackIcon = (props) => (
        <Icon {...props} name='arrow-back'/>
    );

    const renderItemHeader = (headerProps, info) => (
        <View {...headerProps} style={{alignItems: 'center',margin:10}}>
            <Text category='h6' >
                车型： {info.item.cx}        车号： {info.item.ch}
            </Text>
        </View>
    );

//TODO  需要对head 组件进行重新命名
    const renderItemHeaderone = (headerProps, info) => (
        <View {...headerProps} style={{alignItems: 'center',margin:10}}>
            <Text category='h6' >
                车型： {info.item.firstname}        车号： {info.item.ch}
            </Text>
        </View>
    );

    const renderItemFooter = (footerProps,info) => (
            <Button onPress={()=>{
                navigation.navigate('AddTicketCollection',{cx:info.item.cx,ch:info.item.ch,cxid:info.item.cxid,id:info.item.id});
            }} >
                <Text>
                    提票
                </Text>
            </Button>
    );

    /**
     * 选择机车部分
     * @param info
     * @returns {JSX.Element}
     */
    const renderItem = (info) => (
        <Card
            style={styles.item}
            status='basic'
            header={headerProps => renderItemHeader(headerProps, info)}
            footer={footerProps => renderItemFooter(footerProps, info)}>
            <Layout style={styles.textContainer}>
                <Layout style={styles.textItem}>
                    <Text>
                        类型:{info.item.lx}
                    </Text>
                </Layout>
                <Layout style={styles.textItem}>
                    <Text>
                        范围:0
                    </Text>
                </Layout>
                <Layout style={styles.textItem}>
                    <Text>
                        动态:0
                    </Text>
                </Layout>
            </Layout>

            <Layout style={styles.textContainer}>
                <Layout style={styles.textItem}>
                    <Text>
                        乘务:0
                    </Text>
                </Layout>
                <Layout style={styles.textItem}>
                    <Text>
                        普通:0
                    </Text>
                </Layout>
            </Layout>
        </Card>
    );

    /**
     * 以提取活项
     * @param info
     * @returns {JSX.Element}
     */
    const accept = (info) => (
        <Card
            style={styles.item}
            status='success'
            header={headerProps => renderItemHeaderone(headerProps, info)}
            footer={footerProps => renderacceptFooter(footerProps, info)}>

          <Layout style={styles.textContainer}>
              <Layout style={styles.textItem}>
                  <Text>
                     故障名称: {info.item.gzxx}
                  </Text>
              </Layout>
              <Layout style={styles.textItem}>
                  <Text>
                      状态: {info.item.zt}
                  </Text>
              </Layout>

          </Layout>

        </Card>
    );

    const renderacceptFooter = (footerProps,info) => (
        <Button appearance='outline' status='warning' onPress={()=>{

            console.log("删除",info.item.id)
            const  requestOptions = {
                method: 'GET',
                redirect: 'follow'
            };

            const url = "http://htjoa.nrnet.cn/dc14/jwmis/faultdelete/update?id="+info.item.id+"&hxid="+info.item.id+"&hid="+info.item.hid+"&rkid="+info.item.rkid
            console.log(url)
            fetch(url, requestOptions)
                .then(response => response.text())
                .then(result => {
                    console.log(result,"删除结果")
                    if (result==="success"){
                        SorageManager.get('userInf').then(async r => {
                            showToast("删除成功")

                            const s = await AsyncStorage.getItem("search")
                            if (s === undefined) {
                                getExtractedList("", r["userid"])
                            } else {
                                getExtractedList(s, r["userid"])
                            }
                        })

                    }else {
                        showToast("此活项不能删除")
                    }
                })
                .catch(error => console.log('error', error));
        }}>
            删除
        </Button>
    );








    const BackAction = () => (
        <TopNavigationAction icon={BackIcon} onPress={navigateMenu}/>
    );



    return (
        <View style={{ flex: 1 }}>
            <TopNavigation
                accessoryLeft={BackAction}
                title='整备提票' alignment='center' />
            <Divider/>
        <TabView
            selectedIndex={selectedIndex}
            onSelect={(index) => {
                setSelectedIndex(index)
                SorageManager.get('userInf').then(async r => {
                    console.log(r, "userINF")
                    const s = await AsyncStorage.getItem("search")
                    console.log(s)
                    if (s === undefined) {
                        getPreparInfList(r["belongduan"], "")
                        getExtractedList("", r["userid"])
                    } else {
                        getPreparInfList(r["belongduan"], s)
                        getExtractedList(s, r["userid"])
                    }
                })


            }}

        >
            <Tab title='选取机车'>
                <Layout style={styles.tabContainer}>



                    <View style={{flexDirection:'row',justifyContent: 'center',marginTop:10,marginBottom:10}}>

                        <Input
                            onSubmitEditing={Keyboard.dismiss}
                            style={{width:Dimensions.get('window').width-20}}
                            value={value}
                            placeholder='机车号模糊查找'
                            accessoryRight={(<Icon
                                onPress={()=>{
                                    SorageManager.get('userInf').then(async r => {
                                        const s = await AsyncStorage.getItem("search")
                                        console.log(r, "userINf")
                                        getPreparInfList(r["belongduan"], '')
                                        SorageManager.set("search", '')
                                        ToastAndroid.show("取消查询", ToastAndroid.SHORT);
                                        setValue('')

                                    })




                                }}
                                style={styles.icon}
                                fill='#8F9BB3'
                                name='close-outline'
                            />)}
                            // secureTextEntry={secureTextEntry}
                            onChangeText={async nextValue => {
                                setValue(nextValue);
                                console.log(nextValue, "存储值")
                                console.log(typeof nextValue)
                                await AsyncStorage.setItem("search", nextValue)

                            }}
                        />

                        {/*<Input*/}
                        {/*       placeholder='机车号'*/}
                        {/*       value={value}*/}
                        {/*       onChangeText={nextValue => setValue(nextValue)}>*/}
                        {/*</Input>*/}

                    </View>

                    <Divider/>
                    <List
                        style={styles.container}
                        contentContainerStyle={styles.contentContainer}
                        data={trainInf}
                        renderItem={renderItem}
                    />

                </Layout>
            </Tab>

            <Tab title='已提取活项' onPress={()=>{
                console.log("测试以提取")
            }}>
                <Layout style={styles.tabContainer}>
                    <List
                        style={styles.container}
                        contentContainerStyle={styles.contentContainer}
                        data={workInf}
                        renderItem={accept}
                    />

                </Layout>
            </Tab>
        </TabView>

        </View>
    );
};

const styles = StyleSheet.create({
    container: {

    },
    contentContainer: {
        paddingHorizontal: 15,
        // paddingVertical: 4,
    },
    item: {
        marginTop:15,
        // marginVertical: 4,

    },

    tabContainer: {
        // height: 475,
        height: Dimensions.get('window').height-118
    },

    textContainer:{
        flexDirection:'row',
        flexWrap:'wrap',
        justifyContent:"space-evenly",
        alignItems:"center",
        marginBottom:10

    },
    textItem:{
        justifyContent:'center',
        alignItems:'center',

    }
});